package com.truckdispatching.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

import com.truckdispatching.R;
import com.truckdispatching.UserManager;
import com.truckdispatching.http.controller.GetPhotosHttpController;
import com.truckdispatching.http.util.OnResponseHandler;
import com.truckdispatching.http.util.TDHttpController;
import com.truckdispatching.image.ImageLoader;
import com.truckdispatching.image.ImageTask;
import com.truckdispatching.image.ImageTaskHandler;
import com.truckdispatching.image.ImageUploadTask;

/**
 * 上传照片界面
 * 
 * @author Lee
 * @date 2013-4-30
 */
public class UploadUserPictureActivity extends BaseActivity implements OnClickListener {

	private View mBtnIdCardPic;
	private View mBtnDrivePic;
	private View mBtnTravalPic;
	private View mBtnHeadPic;
	private View mBtnBackPic;
	private View mBtnSidePic;

	private ImageView mIdCardPicImage;
	private ImageView mDrivePicImage;
	private ImageView mTravalPicImage;
	private ImageView mHeadPicImage;
	private ImageView mBackPicImage;
	private ImageView mSidePicImage;

	private TextView mIdCardPicTag;
	private TextView mDrivePicTag;
	private TextView mTravalPicTag;
	private TextView mHeadPicTag;
	private TextView mBackPicTag;
	private TextView mSidePicTag;

	private View mBtnOk;
	private View mBtnBack;

	public enum UploadPic {
		PIC_IDCARD, PIC_DRIVE, PIC_TRAVAL, PIC_HEAD, PIC_BACK, PIC_SIDE
	}

	private static UploadPic mCurrentUploadPic;

	private File mImageFileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "truckimage");
	private File mIdCardImageFile = new File(mImageFileDir, "idcard.jpg");
	private File mDriveImageFile = new File(mImageFileDir, "drive.jpg");
	private File mTravalImageFile = new File(mImageFileDir, "traval.jpg");
	private File mHeadImageFile = new File(mImageFileDir, "head.jpg");
	private File mBackImageFile = new File(mImageFileDir, "back.jpg");
	private File mSideImageFile = new File(mImageFileDir, "side.jpg");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload_user_pic_activity);

		mBtnIdCardPic = findViewById(R.id.idcard_layout);
		mBtnIdCardPic.setOnClickListener(this);
		mBtnDrivePic = findViewById(R.id.drive_layout);
		mBtnDrivePic.setOnClickListener(this);
		mBtnTravalPic = findViewById(R.id.traval_layout);
		mBtnTravalPic.setOnClickListener(this);
		mBtnHeadPic = findViewById(R.id.head_layout);
		mBtnHeadPic.setOnClickListener(this);
		mBtnBackPic = findViewById(R.id.back_layout);
		mBtnBackPic.setOnClickListener(this);
		mBtnSidePic = findViewById(R.id.side_layout);
		mBtnSidePic.setOnClickListener(this);

		mIdCardPicImage = (ImageView) findViewById(R.id.idcard_image);
		mIdCardPicImage.setOnClickListener(this);
		mDrivePicImage = (ImageView) findViewById(R.id.drive_image);
		mDrivePicImage.setOnClickListener(this);
		mTravalPicImage = (ImageView) findViewById(R.id.traval_image);
		mTravalPicImage.setOnClickListener(this);
		mHeadPicImage = (ImageView) findViewById(R.id.head_image);
		mHeadPicImage.setOnClickListener(this);
		mBackPicImage = (ImageView) findViewById(R.id.back_image);
		mBackPicImage.setOnClickListener(this);
		mSidePicImage = (ImageView) findViewById(R.id.side_image);
		mSidePicImage.setOnClickListener(this);

		mIdCardPicTag = (TextView) findViewById(R.id.idcard_state);
		mDrivePicTag = (TextView) findViewById(R.id.drive_state);
		mTravalPicTag = (TextView) findViewById(R.id.traval_state);
		mHeadPicTag = (TextView) findViewById(R.id.head_state);
		mBackPicTag = (TextView) findViewById(R.id.back_state);
		mSidePicTag = (TextView) findViewById(R.id.side_state);

		mBtnOk = findViewById(R.id.btn_ok);
		mBtnOk.setOnClickListener(this);

		mBtnBack = findViewById(R.id.btn_back);
		mBtnBack.setOnClickListener(this);

		if (!mImageFileDir.exists()) {
			mImageFileDir.mkdirs();
		}
		GetPhotosHttpController controller = new GetPhotosHttpController();
		controller.setOnResponseListener(new OnResponseHandler() {

			@Override
			public void onResponseError(int errorCode, String errorMessage) {
				dismissLoadingDialog();
			}

			@Override
			public void onResponse(Object response) {
				getPicture();
				dismissLoadingDialog();
			}
		});
		controller.sendRequest();
		showLoadingDialog();
		getPicture();
	}

	private int mColorGreen = Color.rgb(43, 120, 34);
	private int mColorRed = Color.rgb(255, 0, 0);

	private void getPicture() {
		String picIDCard = UserManager.getPicIDCard();
		if (picIDCard != null && !picIDCard.equals("")) {
			ImageTask task = new ImageTask(mIdCardImageFile, picIDCard);
			Bitmap bitmap = ImageLoader.getInstance().loadBitmap(task, new ImageTaskHandler() {

				@Override
				public void success(ImageTask task, Bitmap bitmap) {
					mIdCardPicImage.setImageBitmap(bitmap);
				}

				@Override
				public void fail(ImageTask task) {}
			});
			if (bitmap != null) {
				mIdCardPicImage.setImageBitmap(bitmap);
			}
			mIdCardPicTag.setText("已上传");
			mIdCardPicTag.setTextColor(mColorGreen);
		} else {
			mIdCardPicImage.setImageDrawable(null);
			mIdCardPicTag.setText("未上传");
			mIdCardPicTag.setTextColor(mColorRed);
		}
		String drive = UserManager.getPicDrivingLicence();
		if (drive != null && !drive.equals("")) {
			ImageTask task = new ImageTask(mDriveImageFile, drive);
			Bitmap bitmap = ImageLoader.getInstance().loadBitmap(task, new ImageTaskHandler() {

				@Override
				public void success(ImageTask task, Bitmap bitmap) {
					mDrivePicImage.setImageBitmap(bitmap);
				}

				@Override
				public void fail(ImageTask task) {}
			});
			if (bitmap != null) {
				mDrivePicImage.setImageBitmap(bitmap);
			}
			mDrivePicTag.setText("已上传");
			mDrivePicTag.setTextColor(mColorGreen);
		} else {
			mDrivePicImage.setImageDrawable(null);
			mDrivePicTag.setText("未上传");
			mDrivePicTag.setTextColor(mColorRed);
		}
		String travel = UserManager.getPicTravelLicence();
		if (travel != null && !travel.equals("")) {
			ImageTask task = new ImageTask(mTravalImageFile, travel);
			Bitmap bitmap = ImageLoader.getInstance().loadBitmap(task, new ImageTaskHandler() {

				@Override
				public void success(ImageTask task, Bitmap bitmap) {
					mTravalPicImage.setImageBitmap(bitmap);
				}

				@Override
				public void fail(ImageTask task) {}
			});
			if (bitmap != null) {
				mTravalPicImage.setImageBitmap(bitmap);
			}
			mTravalPicTag.setText("已上传");
			mTravalPicTag.setTextColor(mColorGreen);
		} else {
			mTravalPicImage.setImageDrawable(null);
			mTravalPicTag.setText("未上传");
			mTravalPicTag.setTextColor(mColorRed);
		}
		String back = UserManager.getPicTruckBack();
		if (back != null && !back.equals("")) {
			ImageTask task = new ImageTask(mBackImageFile, back);
			Bitmap bitmap = ImageLoader.getInstance().loadBitmap(task, new ImageTaskHandler() {

				@Override
				public void success(ImageTask task, Bitmap bitmap) {
					mBackPicImage.setImageBitmap(bitmap);
				}

				@Override
				public void fail(ImageTask task) {}
			});
			if (bitmap != null) {
				mBackPicImage.setImageBitmap(bitmap);
			}
			mBackPicTag.setText("已上传");
			mBackPicTag.setTextColor(mColorGreen);
		} else {
			mBackPicImage.setImageDrawable(null);
			mBackPicTag.setText("未上传");
			mBackPicTag.setTextColor(mColorRed);
		}
		String head = UserManager.getPicTruckHead();
		if (head != null && !head.equals("")) {
			ImageTask task = new ImageTask(mHeadImageFile, head);
			Bitmap bitmap = ImageLoader.getInstance().loadBitmap(task, new ImageTaskHandler() {

				@Override
				public void success(ImageTask task, Bitmap bitmap) {
					mHeadPicImage.setImageBitmap(bitmap);
				}

				@Override
				public void fail(ImageTask task) {}
			});
			if (bitmap != null) {
				mHeadPicImage.setImageBitmap(bitmap);
			}
			mHeadPicTag.setText("已上传");
			mHeadPicTag.setTextColor(mColorGreen);
		} else {
			mHeadPicImage.setImageDrawable(null);
			mHeadPicTag.setText("未上传");
			mHeadPicTag.setTextColor(mColorRed);
		}
		String side = UserManager.getPicTruckSideFace();
		if (side != null && !side.equals("")) {
			ImageTask task = new ImageTask(mSideImageFile, side);
			Bitmap bitmap = ImageLoader.getInstance().loadBitmap(task, new ImageTaskHandler() {

				@Override
				public void success(ImageTask task, Bitmap bitmap) {
					mSidePicImage.setImageBitmap(bitmap);
				}

				@Override
				public void fail(ImageTask task) {}
			});
			if (bitmap != null) {
				mSidePicImage.setImageBitmap(bitmap);
			}
			mSidePicTag.setText("已上传");
			mSidePicTag.setTextColor(mColorGreen);
		} else {
			mSidePicImage.setImageDrawable(null);
			mSidePicTag.setText("未上传");
			mSidePicTag.setTextColor(mColorRed);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.idcard_layout:
			mCurrentUploadPic = UploadPic.PIC_IDCARD;
			showChosePicDialog();
			break;
		case R.id.drive_layout:
			mCurrentUploadPic = UploadPic.PIC_DRIVE;
			showChosePicDialog();
			break;
		case R.id.traval_layout:
			mCurrentUploadPic = UploadPic.PIC_TRAVAL;
			showChosePicDialog();
			break;
		case R.id.head_layout:
			mCurrentUploadPic = UploadPic.PIC_HEAD;
			showChosePicDialog();
			break;
		case R.id.back_layout:
			mCurrentUploadPic = UploadPic.PIC_BACK;
			showChosePicDialog();
			break;
		case R.id.side_layout:
			mCurrentUploadPic = UploadPic.PIC_SIDE;
			showChosePicDialog();
			break;
		case R.id.idcard_image: {
			if (!UserManager.getPicIDCard().equals("")) {
				showBigPicDialog(mIdCardImageFile);
			}
			break;
		}
		case R.id.drive_image: {
			if (!UserManager.getPicDrivingLicence().equals("")) {
				showBigPicDialog(mDriveImageFile);
			}
			break;
		}
		case R.id.traval_image: {
			if (!UserManager.getPicTravelLicence().equals("")) {
				showBigPicDialog(mTravalImageFile);
			}
			break;
		}
		case R.id.head_image: {
			if (!UserManager.getPicTruckHead().equals("")) {
				showBigPicDialog(mHeadImageFile);
			}
			break;
		}
		case R.id.back_image: {
			if (!UserManager.getPicTruckBack().equals("")) {
				showBigPicDialog(mBackImageFile);
			}
			break;
		}
		case R.id.side_image: {
			if (!UserManager.getPicTruckSideFace().equals("")) {
				showBigPicDialog(mSideImageFile);
			}
			break;
		}
		case R.id.btn_ok:
		case R.id.btn_back:
			finish();
			break;
		default:
			break;
		}
	}

	private void showBigPicDialog(File file) {
		if (!file.exists()) {
			return;
		}
		Options o = new Options();
		o.inJustDecodeBounds = true;
		o.inPreferredConfig = Bitmap.Config.RGB_565;
		Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), o);
		int width = o.outWidth;
		Options o1 = new Options();
		o1.inPreferredConfig = Bitmap.Config.RGB_565;
		int scale = width / 400;
		if (scale > 1) {
			o1.inSampleSize = scale;
		}
		bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), o1);
		if (bitmap != null) {
			Dialog dialog = new Dialog(this, R.style.dialog);
			ImageView image = new ImageView(this);
			image.setImageBitmap(bitmap);
			dialog.setContentView(image, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		}
	}

	private AlertDialog mChoseDialog = null;

	private void showChosePicDialog() {
		if (mChoseDialog == null) {
			mChoseDialog = new AlertDialog.Builder(this).setTitle("提示").setMessage("选择图片")
				.setPositiveButton("图库", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent();
						/* 开启Pictures画面Type设定为image */
						intent.setType("image/*");
						/* 使用Intent.ACTION_GET_CONTENT这个Action */
						intent.setAction(Intent.ACTION_GET_CONTENT);
						/* 取得相片后返回本画面 */
						startActivityForResult(intent, 1);
					}
				}).setNeutralButton("照相", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(intent, 1);
					}
				}).setNegativeButton("取消", null).create();
		}
		mChoseDialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == 1) {
			Uri uri = data.getData();
			if (uri == null) {
				try {
					Bundle bundle = data.getExtras();
					Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
					if (bitmap != null) {
						File saveFile = null;
						Bitmap thumb = ThumbnailUtils.extractThumbnail(bitmap, 160, 96);
						String type = "";
						if (mCurrentUploadPic == UploadPic.PIC_IDCARD) {
							mIdCardPicImage.setImageBitmap(thumb);
							saveFile = mIdCardImageFile;
							type = "idcPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_DRIVE) {
							mDrivePicImage.setImageBitmap(thumb);
							saveFile = mDriveImageFile;
							type = "dcPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_TRAVAL) {
							mTravalPicImage.setImageBitmap(thumb);
							saveFile = mTravalImageFile;
							type = "vtcPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_HEAD) {
							mHeadPicImage.setImageBitmap(thumb);
							saveFile = mHeadImageFile;
							type = "thPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_BACK) {
							mBackPicImage.setImageBitmap(thumb);
							saveFile = mBackImageFile;
							type = "ttPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_SIDE) {
							mSidePicImage.setImageBitmap(thumb);
							saveFile = mSideImageFile;
							type = "tsPhoto";
						}
						if (saveFile != null) {
							if (saveFile.exists()) {
								saveFile.delete();
							}
							int q = 100 * 500 / bitmap.getWidth();
							if (q > 100) {
								q = 100;
							}
							bitmap.compress(Bitmap.CompressFormat.JPEG, q, new FileOutputStream(saveFile));
							if (saveFile.exists()) {
								// HashMap<String, String> params = new
								// HashMap<String, String>();
								// params.put("jsessionid", UserManager.getToken());
								// params.put("type", type);
								ImageUploadTask task = new
									ImageUploadTask(TDHttpController.mHostUrl + "/wap/uploadPhoto.do?jsessionid=" + UserManager.getToken()
										+ "&type=" + type, null, saveFile);
								task.setUploadListener(new Handler() {
									@Override
									public void handleMessage(Message msg) {
										if (msg.what == 1) {
											String response = msg.obj.toString();
											try {
												JSONObject jo = new JSONObject(response);
												boolean success = jo.getBoolean("success");
												if (success) {
													JSONObject data = jo.getJSONObject("data");
													if (data != null) {
														String url = data.getString("url");
														showToast("上传成功");
														if (mCurrentUploadPic == UploadPic.PIC_IDCARD) {
															UserManager.setPicIDCard(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_DRIVE) {
															UserManager.setPicDrivingLicence(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_TRAVAL) {
															UserManager.setPicTravelLicence(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_HEAD) {
															UserManager.setPicTruckHead(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_BACK) {
															UserManager.setPicTruckBack(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_SIDE) {
															UserManager.setPicTruckSideFace(url);
														}
													} else {
														showToast("上传失败");
													}
												} else {
													String errorMsg = jo.getString("msg");
													showToast("上传失败:" + errorMsg);
												}
											} catch (JSONException e) {
												e.printStackTrace();
												showToast("上传失败");
											}
										} else if (msg.what == 2) {
											dismissLoadingDialog();
											showToast("上传失败");
										}
										getPicture();
										dismissLoadingDialog();
									}
								});
								new Thread(task).start();
								showLoadingDialog();
							}
						}
						bitmap.recycle();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

			} else {
				ContentResolver cr = this.getContentResolver();
				Cursor cursor = null;
				if (cr != null && uri != null) {
					cursor = cr.query(uri, null, null, null, null);
				}
				int angle = 0;
				if (cursor != null) {
					cursor.moveToFirst();// 把游标移动到首位，因为这里的Uri是包含ID的所以是唯一的不需要循环找指向第一个就是了  
					String orientation = cursor.getString(cursor
						.getColumnIndex("orientation"));// 获取旋转的角度  
					cursor.close();
					if (orientation != null && !"".equals(orientation)) {
						angle = Integer.parseInt(orientation);
					}
				}
				try {
					Options o = new Options();
					o.inJustDecodeBounds = true;
					o.inPreferredConfig = Bitmap.Config.RGB_565;
					Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, o);
					int width = o.outWidth;
					Options o1 = new Options();
					o1.inPreferredConfig = Bitmap.Config.RGB_565;
					int scale = width / 500;
					if (scale > 1) {
						o1.inSampleSize = scale;
					}
					bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, o1);
					if (bitmap != null) {
						if (angle != 0) {
							// 下面的方法主要作用是把图片转一个角度，也可以放大缩小等  
							Matrix m = new Matrix();
							int w = bitmap.getWidth();
							int h = bitmap.getHeight();
							m.setRotate(angle); // 旋转angle度  
							Bitmap tempBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true);// 从新生成图片  
							bitmap.recycle();
							bitmap = null;
							bitmap = tempBitmap;
						}
						File saveFile = null;
						Bitmap thumb = ThumbnailUtils.extractThumbnail(bitmap, 160, 96);
						String type = "";
						if (mCurrentUploadPic == UploadPic.PIC_IDCARD) {
							mIdCardPicImage.setImageBitmap(thumb);
							saveFile = mIdCardImageFile;
							type = "idcPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_DRIVE) {
							mDrivePicImage.setImageBitmap(thumb);
							saveFile = mDriveImageFile;
							type = "dcPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_TRAVAL) {
							mTravalPicImage.setImageBitmap(thumb);
							saveFile = mTravalImageFile;
							type = "vtcPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_HEAD) {
							mHeadPicImage.setImageBitmap(thumb);
							saveFile = mHeadImageFile;
							type = "thPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_BACK) {
							mBackPicImage.setImageBitmap(thumb);
							saveFile = mBackImageFile;
							type = "ttPhoto";
						} else if (mCurrentUploadPic == UploadPic.PIC_SIDE) {
							mSidePicImage.setImageBitmap(thumb);
							saveFile = mSideImageFile;
							type = "tsPhoto";
						}
						if (saveFile != null) {
							if (saveFile.exists()) {
								saveFile.delete();
							}
							int q = 100 * 500 / bitmap.getWidth();
							if (q > 100) {
								q = 100;
							}
							bitmap.compress(Bitmap.CompressFormat.JPEG, q, new FileOutputStream(saveFile));
							if (saveFile.exists()) {
								// HashMap<String, String> params = new
								// HashMap<String, String>();
								// params.put("jsessionid", UserManager.getToken());
								// params.put("type", type);
								ImageUploadTask task = new
									ImageUploadTask(TDHttpController.mHostUrl + "/wap/uploadPhoto.do?jsessionid=" + UserManager.getToken()
										+ "&type=" + type, null, saveFile);
								task.setUploadListener(new Handler() {
									@Override
									public void handleMessage(Message msg) {
										if (msg.what == 1) {
											String response = msg.obj.toString();
											try {
												JSONObject jo = new JSONObject(response);
												boolean success = jo.getBoolean("success");
												if (success) {
													JSONObject data = jo.getJSONObject("data");
													if (data != null) {
														String url = data.getString("url");
														showToast("上传成功");
														if (mCurrentUploadPic == UploadPic.PIC_IDCARD) {
															UserManager.setPicIDCard(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_DRIVE) {
															UserManager.setPicDrivingLicence(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_TRAVAL) {
															UserManager.setPicTravelLicence(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_HEAD) {
															UserManager.setPicTruckHead(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_BACK) {
															UserManager.setPicTruckBack(url);
														} else if (mCurrentUploadPic == UploadPic.PIC_SIDE) {
															UserManager.setPicTruckSideFace(url);
														}
													} else {
														showToast("上传失败");
													}
												} else {
													String errorMsg = jo.getString("msg");
													showToast("上传失败:" + errorMsg);
												}
											} catch (JSONException e) {
												e.printStackTrace();
												showToast("上传失败");
											}
										} else if (msg.what == 2) {
											dismissLoadingDialog();
											showToast("上传失败");
										}
										getPicture();
										dismissLoadingDialog();
									}
								});
								new Thread(task).start();
								showLoadingDialog();
							}
						}
						bitmap.recycle();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
